package com.carbohydrate42.kotlin_compose_demo.compose

import android.content.Context
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview

/**
 * sharedPreference 共享偏好, 参考
 * https://developer.android.google.cn/training/data-storage/shared-preferences
 * https://blog.csdn.net/huweiliyi/article/details/105496932#:~:text=SharedPreferences%E6%A6%82%E8%BF%B0%20SharedPreferences%20%E6%98%AFAndroid%E5%B9%B3%E5%8F%B0%E4%B8%8A%E4%B8%80%E4%B8%AA%E8%BD%BB%E9%87%8F%E7%BA%A7%E7%9A%84%E5%AD%98%E5%82%A8%E8%BE%85%E5%8A%A9%E7%B1%BB%EF%BC%8C%E7%94%A8%E6%9D%A5%E4%BF%9D%E5%AD%98%E5%BA%94%E7%94%A8%E7%9A%84%E4%B8%80%E4%BA%9B%E5%B8%B8%E7%94%A8%E9%85%8D%E7%BD%AE%EF%BC%8C%E5%AE%83%E6%8F%90%E4%BE%9B%E4%BA%86%20String%20%EF%BC%8C%20set%20%EF%BC%8C%20int,float%20%EF%BC%8C%20boolean%20%E5%85%AD%E7%A7%8D%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E3%80%82%20SharedPreferences%20%E7%9A%84%E6%95%B0%E6%8D%AE%E4%BB%A5%E9%94%AE%E5%80%BC%E5%AF%B9%E7%9A%84%E8%BF%9B%E8%A1%8C%E4%BF%9D%E5%AD%98%E5%9C%A8%E4%BB%A5%20xml%20%E5%BD%A2%E5%BC%8F%E7%9A%84%E6%96%87%E4%BB%B6%E4%B8%AD%E3%80%82
 */
@Preview(showBackground = true, showSystemUi = true)
@Composable
fun TrySharedPreference() {
    val current = LocalContext.current

    val sharedPref = current.getSharedPreferences("demo_application", Context.MODE_PRIVATE)

    var value1 by remember {
        mutableStateOf(1)
    }

    var value2 by remember {
        mutableStateOf("")
    }

    Column() {
        Button(onClick = {
            /**
             * 存的内容可以在手机的 data/data/包名/shared_prefs 里面找到一个 demo_application.xml 的文件
             */
            with(sharedPref.edit()) {
                putInt("key1", 2)
                putString("key2", "value2")
                apply()
            }
        }) {
            Text(text = "save to share preference")
        }

        Button(onClick = {
            value1 = sharedPref.getInt("key1", -1)
        }) {
            Text(text = "read key1")
        }

        Button(onClick = {
            /**
             * getString 和其他的 get 方法的第二个参数是给一个默认值, 但 kotlin 好像不大能识别 java 写的代码
             */
            value2 = sharedPref.getString("key2", "") ?: ""
        }) {
            Text(text = "read key1")
        }

        Text(text = value1.toString())
        Text(text = value2)
    }
}